package com.simplehire.controller;

import com.simplehire.dto.UserRegistrationDto;
import com.simplehire.model.User;
import com.simplehire.model.UserRole;
import com.simplehire.service.UserService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;

@Controller
@RequestMapping("/")
public class AuthController {
    
    private final UserService userService;
    
    public AuthController(UserService userService) {
        this.userService = userService;
    }
    
    @GetMapping("login")
    public String login() {
        return "login";
    }
    
    @GetMapping("register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new UserRegistrationDto());
        return "register";
    }
    
    @PostMapping("register")
    // 在registerUser方法中，修改用户创建逻辑
    public String registerUser(@Valid @ModelAttribute("user") UserRegistrationDto userDto, BindingResult result, Model model) 
    {
        if (result.hasErrors()) {
        return "register";
        }
    
        if (userService.userExists(userDto.getUsername())) {
        model.addAttribute("error", "用户名已存在");
        return "register";
        }
    
        if (userService.emailExists(userDto.getEmail())) {
        model.addAttribute("error", "邮箱已被注册");
        return "register";
        }
    
        try {
        // 默认注册为普通用户
        User user = new User(
            userDto.getUsername(),
            userDto.getPassword(),
            userDto.getEmail(),
            Arrays.asList(UserRole.USER) // 默认注册为普通用户
        );
        userService.save(user);
        return "redirect:/login?success";
    } catch (Exception e) {
        model.addAttribute("error", "注册失败: " + e.getMessage());
        return "register";
    }
}
}